package com.kedacom.demo.hmac;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HMACClient {

	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	private static final Logger logger = LoggerFactory.getLogger(HMACClient.class);

	public static void main(String[] args) throws HttpException, IOException, NoSuchAlgorithmException {
		makeHTTPCallUsingHMAC("Jack", "888");
	}

	public static void makeHTTPCallUsingHMAC(String username, String secret) throws HttpException, IOException {
		String contentToEncode = "{\"comment\" : {\"message\":\"blaat\" , \"from\":\"blaat\" , \"commentFor\":123}}";
		String contentType = "application/vnd.geo.comment+json";
		String currentDate = new SimpleDateFormat(DATE_FORMAT).format(new Date());
		HttpPost post = new HttpPost("http://localhost:8080/demo-hmac/index.jsp");
		StringEntity data = new StringEntity(contentToEncode, contentType, "UTF-8");
		post.setEntity(data);
		String httpMethod = post.getMethod();
		String contentMd5 = DigestUtils.md5Hex(contentToEncode);
		String toSign = HMACUtils.populateHMACContent(httpMethod, contentMd5, data.getContentType().getValue(),
				currentDate, post.getURI().getPath());
		String hmac = HMACUtils.calculateHMAC(secret, toSign);
		logger.debug("hmac content: {}", toSign);

		post.addHeader(HMACUtils.HMAC_HEAD_NAME, username + ":" + hmac);
		post.addHeader("Date", currentDate);
		post.addHeader("Content-Md5", contentMd5);

		HttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(post);
		logger.debug("client response: {}", response.getStatusLine().getStatusCode());
	}

}
